<template>
    <div class="search">
        <el-autocomplete 
        class="search-input"
        v-model="currentName"
        placeholder="请输入企业名称"
        clearable
        @select="handleSelect"
        :fetch-suggestions="fetchHistorySuggestion"
        :maxlength="100"
        >
            <div 
            v-if="item.type === 'group-title'"
            class="group-title"
            slot-scope="{ item }"
            @click.prevent.stop
            >
                {{item.value}}
            </div>

            <div 
            class="suggest-item" 
            slot-scope="{ item }"
            v-else-if="item.id"
            >   
            <el-tooltip class="item" effect="dark" :content="item.value" :disabled="contentShow(item.value)" placement="left">
                 <div class="value">{{ item.value }}</div>
            </el-tooltip>
            </div>

            <div 
            class="history-item" 
            slot-scope="{ item }"
            v-else
            >   
            <el-tooltip class="item" effect="dark" :content="item.value" :disabled="contentShow(item.value)" placement="left">
                 <div class="value">{{ item.value }}</div>
            </el-tooltip>
                <span class="icon" v-if="item.type == 'history'">
                    <i 
                        class="el-icon-close"
                        @click.stop="delTheHistory(item)"
                    ></i>
                </span>
            </div>

            <el-button 
                type="primary"
                slot="append"
                icon="el-icon-search"
                @click="clickHandler"
            ></el-button>
        </el-autocomplete>
    </div>
</template>

<script>

export default {
    props:{},
    data() {
        return {
            questionVisible: false,
            currentName:'',//当前名称

            historyList: [],
            suggestList: [],

            selectObj:{}, //当前查询对象
        };
    },
    computed: {
    },
    methods: {
        /**
         * 搜索
         */
        clickHandler() {
            const that = this

            if(!this.selectObj.type || !this.currentName){
                this.$emit('selectCompany',"")
                ShowMsg("请在搜索推荐/搜索历史中选择要查询的企业", "warning");
                return
            }
   
            this.$emit('selectCompany',this.currentName,this.selectObj.code)
            if(!!this.selectObj.type){
                this.$ajax({
                type: "get",
                url: `${this.$store.state.api.searchUrl}/searchcompany/saveCompanyRecord`,
                data: {
                    corpName:that.currentName,
                    code:that.selectObj.id
                },
                callback: function (data) {
                    ShowMsg("查询成功", "success");
                },
                error: function () {},
            });
            }
        },
        handleSelect(item) {
           this.currentName = item.value;
           this.selectObj = item || {};

           this.clickHandler();
        },
        /**
         * 获取搜索记录 
         * @param {Function} cb 回调 
         */
        getSearchHistory(cb) {
            const that = this;
            this.$ajax({
                type: "get",
                url: `${this.$store.state.api.searchUrl}/searchcompany/companyrecord`,
                data: {
                },
                callback: function (data) {
                    that.historyList = data || [];
                    cb&&cb()
                },
                error: function () {},
            });
            // cb && cb()
        },
        /**
         * 模糊查询企业名称 返回推荐列表
         * @param {String} name 名称
         * @param {Function} cb 回调 
         */
        
        getSearchNow(name,cb) {
            var that = this;
            var historyNameArr = this.historyList.map(item => item.corpname);

            if(!historyNameArr.includes(name)){
                that.selectObj = {}
            };

            this.$ajax({
                type: "get",
                url: `${this.$store.state.api.searchUrl}/searchcreditchina/creditchina/search`,
                data: {
                    corpName:name,
                    pageNo:1,
                    pageSize:10
                },
                callback: function (data) {
                    that.suggestList = data.list || [];
                     cb&&cb()
                },
            });

            // cb && cb()
        },
        /**
         * 删除历史记录
         * @param {Object} item 所删除对象
         */
        delTheHistory(item) {
            const that = this
            this.$confirm("删除记录, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.$ajax({
                    type: "get",
                    url: `${that.$store.state.api.searchUrl}/searchcompany/deleteById`,
                    data: {
                        id:item.guid
                    },
                    callback: function (data) {
                        ShowMsg("删除成功", "success");
                    },
                    error: function () {},
                });
            });
        },
        /**
         * 匹配输入建议
         */
        fetchHistorySuggestion(queryString, cb) {
            const that = this
            var results = []
            
            // 
            var resFun = function(){
                // 如果没有输入则显示历史记录
                var res1 = that.historyList.length > 0 ? [
                    {
                        type: 'group-title',
                        value: '搜索历史',
                        disabled: true,
                    },
                    ...that.historyList.map(text => {
                        return {
                            value: text.corpname,
                            code: text.code,
                            guid: text.id,
                            type: 'history'
                        };
                    }),
                ] : [
                        {
                            type: 'group-title',
                            value: '无历史记录',
                            disabled: true,
                        }
                ];

                // 如果已输入则显示输入提示
                var res2 = [
                    ...that.suggestList.map(text => {
                        return {
                            value: text.accurate_entity_name,
                            code: text.accurate_entity_code,
                            id: text.accurate_entity_code,
                            type: 'now'
                        };
                    })
                ];


                results = queryString.length > 0 ? res2 : res1
                // 调用 callback 返回建议列表的数据
                cb(results);
            }
            
            if(!!queryString){
                that.getSearchNow(queryString,resFun)
            }else{
                that.getSearchHistory(resFun)
            }
        },

        /** 
         * 是否显示文字提示
         * @param {String} val 传入的文字
         * @param {Number} maxNum 字数临界值
        */
        contentShow(val,maxNum){
            const textLength = val.length;
            let num = maxNum || 31
            return textLength > num ? false : true
        },
    },
    mounted() {
        var name = this.getQuery('name')
        if(!!name){
            this.currentName = name
        }
    }
}
</script>

<style lang="scss" scoped>
    @import '@css/var.scss';

    .search{
        float: left;
        // margin-top: 18px;
        // margin-left: 70px;

        .search-input{
            width: 460px;
            vertical-align: middle;

            ::v-deep {
                .el-input__inner{
                    color: #999999;
                    border-right: none;
                    height: 34px;
                    font-size: 12px;

                    &:focus + .el-input-group__append{
                        border-color: $primaryColor;
                    }
                }

                .el-input-group__append{
                    background-color: $primaryColor;
                    border-color: $primaryColor;
                    color: white;
                    font-size: 16px;
                    padding: 0 16px;
                    transition: .3s border-color;
                }
            }
        }
    }

    .group-title{
        font-size: 12px;
        color: $infoColor;
        line-height: 30px;
        margin: 0 -20px;
        padding: 0 20px;
        position: relative;

        &:after{
            content: '';
            display: block;
            height: 1px;
            background: $infoColor2;
            position: absolute;
            left: 20px;
            right: 20px;
            bottom: 0;
        }
    }
    .suggest-item {
        .value{
            text-overflow: ellipsis;
            overflow: hidden;
        }
    }

    .history-item{
        display: flex;

        .value{
            flex: 1;
            text-overflow: ellipsis;
            overflow: hidden;
        }

        .icon{
            &:hover{
                color: $primaryColor;
            }
        }
    }
</style>